import { defineStore } from 'pinia'
import router from "@/router"

// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const useStore = defineStore('main', {
    // 推荐使用 完整类型推断的箭头函数
    state: () => {
        return {
            hasRoutes: false,
            token: null, // 初始化为 null
            editableTabsValue: '/index',
            menuList: [],
            userInfo: null,
            editableTabs: [
                {
                    title: '首页',
                    name: '/index',
                }
            ]
        }
    },
    actions: {
        GET_USERINFO() {
            console.log("userInfo",this.userInfo,JSON.parse(sessionStorage.getItem("userInfo")));
            
            return this.userInfo || JSON.parse(sessionStorage.getItem("userInfo"))
        },
        GET_TOKEN() {
            return this.token || sessionStorage.getItem("Authorization");
        },
        SET_USERINFO(user) {
            this.userInfo = user
            sessionStorage.setItem("userInfo", JSON.stringify(user));
        },
        SET_TOKEN(token) {
            this.token = token
            sessionStorage.setItem("Authorization", token)
        },
        SET_MENULIST(menuList) {
            this.menuList = menuList;
        },
        SET_ROUTES_STATE(hasRoutes) {
            this.hasRoutes = hasRoutes
        },
        ADD_TABS(tab) {
            if (this.editableTabs.findIndex(e => e.name === tab.path) === -1) {
                this.editableTabs.push({
                    title: tab.name,
                    name: tab.path
                })
            }
            this.editableTabsValue = tab.path
        },
        RESET_TABS() {
            this.editableTabsValue = '/index';
            this.editableTabs = [
                {
                    title: '首页',
                    name: '/index'
                }
            ]
        },
        logout() {
            this.token = null
            window.sessionStorage.clear();
            router.replace("/login")
        }
    },
})